<template>
  <div class="">
    <div style="text-align: center;margin-bottom: 20px;font-size: 18px;font-weight: 700;"><i class="el-icon-cpu"></i>
      POS款机模拟器
    </div>
    <div class="board">
      <el-form labelPosition="left" label-width="80px">
        <el-form-item label="请求地址">
          <div class="board-item">

            <el-input v-model="comAddress">
              <template slot="prepend">ws://</template>
            </el-input>
            <el-button @click="modifyURL" type="info">修改</el-button>
          </div>
        </el-form-item>
        <div class="new-shop">
          <el-input v-model="newShopCode" placeholder="输入门店编码..."></el-input>
          <el-button type="primary" @click="newShop" @keydown.enter.native="newShop">新增门店</el-button>
        </div>
      </el-form>
      <el-input v-model="httpAddress" placeholder="http通讯"></el-input>
      <el-button @click="newHttp">请求</el-button>

    </div>
    <div class="shop-container">

      <div class="shop-message-box" v-for="shop in shops" :key="shop.shopCode">
        <div class="shop-info">
          <div class="title">
            <div class="title-box">
              <div :class="shop.open?'status active':'status'">
                <i class="el-icon-s-shop" style="font-size: 26px"></i>
                <div class="online "></div>
              </div>
              <div class="shop-name">
                <div class="shop-code">{{ shop.shopCode }}</div>
              </div>
            </div>
            <div class="function">
              <i class="el-icon-close" @click="removeShop(shop)"></i>
            </div>
          </div>
          <el-button v-if="!shop.open" size="small" type="primary" @click="connect(shop)">连接</el-button>
          <el-button v-if="shop.open" size="small" type="danger" @click="disconnect(shop)">断开</el-button>
          <!--                <el-switch-->
          <!--                        v-model="shop.open"-->
          <!--                        active-color="#13ce66"-->
          <!--                        inactive-color="#ff4949"-->
          <!--                        @change="handleSession($event,shop)"-->

          <!--                >-->
          <!--                </el-switch>-->
        </div>

        <div class="messages">
          <div class="message" v-for="(message,index) in shop.messages" :key="message.time">
            <div class="message-time">
              {{ message.time }}
            </div>
            <div class="message-content">
              <pre :id="'message_'+shop.shopCode+'_'+index">{{ message.content }}</pre>
            </div>
            <div class="copy">
              <el-button size="mini" circle icon="el-icon-document-copy"
                         @click="copy('message_'+shop.shopCode+'_'+index)"></el-button>
            </div>
          </div>
        </div>
      </div>

    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'POS',
  data() {
    return {
      shops: [

        {
          shopCode: '000001', open: false, session: null,
          messages: []
        }, {
          shopCode: '000002', open: false, session: null,
          messages: []
        }, {
          shopCode: '000003', open: false, session: null,
          messages: []
        },

      ],
      comAddress: '49.232.8.127:9981',
      httpAddress: "47.103.129.175:9984",
      newShopCode: ''
    }
  }, created() {
    let shopsStr = localStorage.getItem("shops");
    let address = localStorage.getItem("address");
    if (address != null) {
      this.comAddress = address
    }
    console.log(shopsStr)
    if (shopsStr != null) {
      let shops = JSON.parse(shopsStr);
      this.shops = shops;
    }
  },
  methods: {
    newHttp() {
      axios.get("http://"+this.httpAddress).then(res=>{
        console.log(res);
      })
    },
    modifyURL() {
      localStorage.setItem("address", this.comAddress)
      this.$message({
        showClose: true,
        message: '地址修改成功',
        type: 'success'
      });
    },
    removeShop(shop) {
      if (this.shops.indexOf(shop) != -1) {

        this.shops.splice(this.shops.indexOf(shop), 1);
        localStorage.setItem("shops", JSON.stringify(this.shops))

      }
    },
    newShop() {
      if (this.newShopCode.length == 0) return
      let shop = {
        shopCode: this.newShopCode, open: false, session: null,
        messages: []
      }
      this.shops.push(shop)
      localStorage.setItem("shops", JSON.stringify(this.shops))
      this.newShopCode = ''
    },
    copy(id) {
      let content = document.getElementById(id).innerText;
      let clip = document.createElement('input');
      clip.value = content;
      document.body.appendChild(clip);
      clip.select();
      document.execCommand('Copy');
      clip.parentNode.removeChild(clip);

      this.$message({
        showClose: true,
        message: '内容已复制到剪切板！',
        type: 'success'
      });

    },
    connect(shop) {
      this.openSocket(shop)
    }, disconnect(shop) {
      this.closeSocket(shop)
    },

    closeSocket(shop) {
      shop.session.close();

    },
    onlineSuccess(shop) {
      shop.open = true
      this.$message({
        showClose: true,
        message: '门店 ' + shop.shopCode + ' 上线成功',
        type: 'success'
      });

    },
    keepAlive(session) {
      session.send("online");
      return setInterval(() => {
        session.send("online")
      }, 5000)

    },

    offLineSuccess(shop) {
      shop.open = false
      this.$message({
        showClose: true,
        message: '门店 ' + shop.shopCode + '已下线',
        type: 'success'
      });
      window.clearInterval(shop.heartBeats)
    },
    openSocket(shop) {
      // let shopCode = shop.shopCode;
      let ws = new WebSocket("ws://" + this.comAddress + "/order");
      shop.session = ws;
      ws.onopen = (e) => {
        console.log(e);
        this.onlineSuccess(shop)
        shop.heartBeats = this.keepAlive(ws)
      }

      ws.onmessage = (e) => {
        let data = e.data;
        let mqObj = JSON.parse(data);

        shop.messages.unshift({time: new Date().toLocaleString(), content: JSON.stringify(mqObj, null, 2)});
      }
      ws.onclose = () => {

        this.offLineSuccess(shop)
      }
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>

</style>
